import {
  ScoreSubmitParamData,
  scoreBySelfTemporarySave,
  selectPmData,
  scoreBySelfSubmit,
  AnnexData
} from '@/api/myPerformance'
import {CCard} from '@/components/card'
import {TargetWeight} from '@/components/input/targetWeight'
import ScoreSummarizeModal from '@/components/modal/scoreSummarizeModal'
import {PMContent, PMLayout, PMNav} from '@/components/others/layout'
import {SplitLine} from '@/components/splitLine'
import {CnBoldSpan, CnMediumP, CnNormalP, CnNormalSpan} from '@/components/text'
import {useLoading} from '@/hooks/loading'
import useModal from '@/hooks/modalHook'
import {useRouteQuery} from '@/hooks/pageRedirect'
import useMyPm from '@/hooks/pm/myPm'
import useOwner from '@/hooks/pm/owner'
import useProgress from '@/hooks/pm/progress'
import {useTableLoading} from '@/hooks/tableHook'
import {ant_design_vue} from '@/libs/global/antDesignVue'
import {SelfScoreQuery} from '@/libs/pageRedirect'
import {unReplaceBreak, replaceBreak, zeroize, checkValueIsInRange} from '@/libs/toolkit'
import {baseUrl} from '@/libs/baseUrl'
import {ddGetAuth, ddUploadFile} from '@/api/dd'
import {defineComponent, reactive, computed, onMounted} from 'vue'
const {message} = ant_design_vue

interface CustomPmTarget extends MyPm.PmTarget {
  score: number | undefined
  scoreContent: string
  scoreDesc: string
}

interface CustomPmData extends Omit<MyPm.PmData, 'pmTargetList'> {
  pmTargetList: CustomPmTarget[]
}

export default defineComponent({
  name: 'scoreBySelf',
  setup(props, ctx) {
    const {getQueryData, router} = useRouteQuery({
      queryKeys: ['defaultPmId']
    })
    const queryData = getQueryData<SelfScoreQuery>()
    if (!queryData) {
      router.back()
      return () => (
        <PMLayout>
          <PMNav></PMNav>
          <PMContent></PMContent>
        </PMLayout>
      )
    }
    const {defaultPmId} = queryData

    const {loading, startLoading, closeLoading} = useTableLoading()

    const {updatePmProgress, pmProgress, scoreSelfByLoginUser, loginUser} = useProgress({
      pmId: defaultPmId
    })

    const {pm, getPmByPmId, setPm} = useMyPm()

    const {owner, udpateOwner} = useOwner()

    const {
      loading: submitLoading,
      startLoading: submitStartLoading,
      closeLoading: submitCloseLoading
    } = useLoading()

    const {
      visible: scoreSummarizeVisible,
      openModal: openScoreSummarizeModel,
      closeModal: closeScoreSummarize
    } = useModal()

    let state = reactive<{
      /**当前绩效的维度列表 */
      pmDataList: CustomPmData[]

      owner: User.Info | null

      /**评分总结 */
      summarize: string

      /**附件 */
      fileList: {
        uid: string // 文件唯一标识，建议设置为负数，防止和内部产生的 id 冲突
        name: string // 文件名
        status: 'uploading' | 'done' | 'error' | 'removed' // 状态有：uploading done error removed
      }[]
      /**已上传附件 */
      annexDataList: AnnexData[]
    }>({
      pmDataList: [],
      owner: null,
      summarize: '',
      annexDataList: [],
      fileList: []
    })

    const submitTargetsList = computed<ScoreSubmitParamData[][]>(() => [])

    /**表格头 */
    const tableColumns = computed<CColumn<CustomPmTarget>[]>(() => {
      let columns: CColumn<CustomPmTarget>[] = [
        {
          title: '指标名称',
          dataIndex: 'pmTargetName',
          width: 'auto',
          ellipsis: true
        },
        {
          title: '权重(%)',
          dataIndex: 'pmTargetWeight',
          width: 80,
          align: 'center',
          ellipsis: true
        },
        {
          title: '考核标准',
          dataIndex: 'pmTargetStand',
          ellipsis: true
        },
        {
          title: '自评',
          dataIndex: 'score',
          width: 180,
          ellipsis: true
        },
        {
          title: '评分说明',
          dataIndex: 'scoreContent',
          width: 220,
          ellipsis: true
        }
      ]
      return columns
    })

    const scoreCount = computed(() => {
      let num = (eval(
        (state.pmDataList || [])
          .map(item =>
            item.pmTargetList.map(target => {
              if (target.isBonus === 0) {
                return (target.score || 0) * (target.pmTargetWeight / 100)
              } else {
                return target.score || 0
              }
            })
          )
          .flat(Infinity)
          .join('+')
      ) || 0) as number

      let returnData = zeroize(num, 2, true)

      return returnData
    })

    // /**根据props.userDDId查询当前绩效所属用户信息 */
    // function getOwnerInfo() {

    //   getUserInfoByUserDDId({userDDId: ownerDDId})
    //     .then(res => {
    //       state.owner = res.data
    //     })
    //     .catch(err => {})
    // }

    function getTableData() {
      startLoading()
      /**获取个人绩效中的维度及指标数据 */
      selectPmData({pmId: Number(defaultPmId)})
        .then(res => {
          if (!res.data || (res.data && res.data.length === 0)) {
            state.pmDataList = []
          } else {
            res.data.sort((a, b) => a.sort - b.sort)
            const pmDataList: CustomPmData[] = res.data.map(item => ({
              pmId: item.pmId,
              pmDimensionId: item.pmDimensionId,
              pmDimensionName: item.pmDimensionName,
              pmDimensionTypeCode: item.pmDimensionTypeCode,
              pmDimensionWeight: item.pmDimensionWeight,
              isCustomSelf: item.isCustomSelf,
              isImport: item.isImport,
              sort: item.sort,
              pmTargetList: item.pmTargetList.map(target => {
                let scoreSelf = target.scoreSelfCheckList?.find(
                  item => item && item.makeUserDDId === loginUser.value.userId
                )
                const obj = {
                  score: scoreSelf?.score || undefined,
                  scoreContent: target.selfContentTem ? target.selfContentTem : '',
                  scoreDesc: ''
                }
                return Object.assign(target, obj)
              })
            }))

            state.pmDataList = pmDataList
            console.log('个人绩效中有数据', res.data)
          }

          closeLoading()
        })
        .catch(err => {
          closeLoading()
        })
    }

    function combScoreBySelfSubmitParamData(data: CustomPmData[]): ScoreSubmitParamData[] | false {
      if (!scoreSelfByLoginUser.value) return []

      let returnData: ScoreSubmitParamData[] = []

      for (let i = 0; i < data.length; i++) {
        const dimension = data[i]
        for (let ii = 0; ii < dimension.pmTargetList.length; ii++) {
          const target = dimension.pmTargetList[ii]

          if (target.pmDimensionId === -1) continue

          if (target.score === undefined) {
            if (target.isBonus === 1) {
              returnData.push({
                makeUserDDId: loginUser.value.userId,
                makeUserName: loginUser.value.userName,
                pmProgressId: scoreSelfByLoginUser.value.pmProgressId,
                pmTargetId: target.pmTargetId,
                score: target.score || 0,
                scoreContent: target.scoreContent,
                scoreDesc: ''
              })
            } else {
              message.warning(
                `维度：${dimension.pmDimensionName}中，指标：${target.pmTargetName}的自评未输入`
              )
              return false
            }
          } else {
            if (target.isBonus === 1 && !checkValueIsInRange(target.score, target.pmTargetRange)) {
              message.warning(
                `维度：${dimension.pmDimensionName}中，加分项：${target.pmTargetName}的自评不在范围内。当前加分项范围为：${target.pmTargetRange}`
              )
              return false
            }

            returnData.push({
              makeUserDDId: loginUser.value.userId,
              makeUserName: loginUser.value.userName,
              pmProgressId: scoreSelfByLoginUser.value.pmProgressId,
              pmTargetId: target.pmTargetId,
              score: target.score || 0,
              scoreContent: target.scoreContent,
              scoreDesc: ''
            })
          }
        }
      }
      return returnData
    }

    function handleSubmitClick(data?: {value: string}) {
      // openScoreSummarizeModel()

      handleScoreSummarizeConfirm(state.summarize)
    }

    function handleScoreSummarizeConfirm(data?: string) {
      if (!scoreSelfByLoginUser.value) return

      let paramData = combScoreBySelfSubmitParamData(state.pmDataList)

      if (!paramData) return

      for (let i = 0; i < state.fileList.length; i++) {
        const file = state.fileList[i]
        if (file.status !== 'done') {
          message.warning('文件未上传结束，请等待！')
          return
        }
      }
      console.log('自评提交', {
        pmProgressId: scoreSelfByLoginUser.value.pmProgressId,
        data: paramData,
        scoreSummary: replaceBreak(data ? data : ''),
        annexData: state.annexDataList
      })

      startLoading()

      scoreBySelfSubmit({
        pmProgressId: scoreSelfByLoginUser.value.pmProgressId,
        data: paramData,
        scoreSummary: replaceBreak(data ? data : ''),
        annexData: state.annexDataList
      })
        .then(res => {
          closeLoading()
          router.back()
        })
        .catch(err => {
          closeLoading()
          getPageData()
        })
    }

    function handleTemporarySaveClick() {
      if (!scoreSelfByLoginUser.value) return
      let data = combScoreBySelfSubmitParamData(state.pmDataList)
      if (!data) return
      scoreBySelfTemporarySave({
        pmProgressId: scoreSelfByLoginUser.value.pmProgressId,
        data: data
      })
        .then(res => {
          getPageData()
        })
        .catch(err => {})
    }

    function getPageData() {
      getPmByPmId({
        pmId: Number(defaultPmId),
        updatePm: true,
        success: data => {
          udpateOwner({ownerDDId: data.pmUserDDId})
        }
      })
      getTableData()
      updatePmProgress({pmId: defaultPmId})
    }

    onMounted(() => {
      getPageData()
    })

    return () => (
      <PMLayout spinning={loading.value}>
        <PMNav>
          <div class='h-full flex items-center'>
            <div class='flex-1 flex items-center'>
              <SplitLine class='mr-16 py-12'></SplitLine>
              <div class='flex-1'>
                {/* owner-msg */}
                {state.owner ? (
                  <span class='flex items-center gap-x-10'>
                    <span class='bg-black rounded-4 overflow-hidden'>
                      {state.owner.avatar ? (
                        <img src={state.owner.avatar || ''} class='w-40 h-40'></img>
                      ) : (
                        <div class='w-40 h-40'>
                          <a-empty></a-empty>
                        </div>
                      )}
                    </span>
                    <span>
                      <CnNormalP class='text-text'>{state.owner.userName}</CnNormalP>
                      <CnNormalP class='text-12'>{state.owner.deptName}</CnNormalP>
                    </span>
                  </span>
                ) : null}
              </div>
            </div>
            <div class='flex items-center gap-x-12'>
              {/* <a-button onClick={handleTemporarySaveClick}>暂存</a-button> */}
              <a-button class=' bg-primary text-white' type='primary' onClick={handleSubmitClick}>
                提交
              </a-button>
            </div>
          </div>
        </PMNav>
        <PMContent>
          <CCard
            title={pm.value?.pmFormName || ''}
            v-slots={{
              title: () => <CnMediumP class='pl-12'>{pm.value?.pmFormName || ''}</CnMediumP>
            }}
            class='px-12 border-0'
          >
            <SplitLine class='w-full h-1 p-0 mb-8'></SplitLine>

            {/* 指标显示区域 */}
            <div class='flex flex-col items-center gap-y-16'>
              {state.pmDataList
                ? state.pmDataList.map((item, dimensionIdx) => (
                    <CCard
                      title={`${item.pmDimensionName}(${item.pmDimensionWeight}%)`}
                      showShadow={false}
                      class='w-full px-12 border-infoLight'
                      style={{
                        background: 'linear-gradient(rgb(236, 245, 255) 0%, rgb(255, 255, 255) 10%)'
                      }}
                      v-slots={{
                        title: () => (
                          <CnMediumP>{`${item.pmDimensionName}(${item.pmDimensionWeight}%)`}</CnMediumP>
                        )
                      }}
                    >
                      <a-table
                        class='custom-table'
                        bordered
                        pagination={false}
                        dataSource={item.pmTargetList}
                        columns={tableColumns.value}
                      >
                        {{
                          bodyCell: ({text, record, column, index}: CBodyCell<CustomPmTarget>) => {
                            switch (column.dataIndex) {
                              case 'score':
                                return (
                                  <div
                                    class='p-16'
                                    style={{
                                      width: column.width + 'px'
                                    }}
                                  >
                                    <TargetWeight
                                      v-model={[
                                        state.pmDataList[dimensionIdx].pmTargetList[index].score,
                                        'value'
                                      ]}
                                      showUnit={false}
                                      placeholder={
                                        record.isBonus === 1
                                          ? record.pmTargetRange
                                            ? '加分项输入范围：' + record.pmTargetRange
                                            : undefined
                                          : undefined
                                      }
                                    ></TargetWeight>
                                  </div>
                                )
                              case 'scoreContent':
                                return (
                                  <div
                                    class='p-16'
                                    style={{
                                      width: column.width + 'px'
                                    }}
                                  >
                                    <a-textarea
                                      v-model={[
                                        state.pmDataList[dimensionIdx].pmTargetList[index]
                                          .scoreContent,
                                        'value'
                                      ]}
                                      class='rounded-4'
                                      rows={1}
                                    ></a-textarea>
                                  </div>
                                )
                              default:
                                return (
                                  <CnNormalP
                                    class='p-16 text-12'
                                    style={{
                                      width: column.width + 'px',
                                      whiteSpace: 'break-spaces'
                                    }}
                                  >
                                    {unReplaceBreak(text + '')}
                                  </CnNormalP>
                                )
                            }
                          }
                        }}
                      </a-table>
                    </CCard>
                  ))
                : null}
            </div>
          </CCard>

          <CCard
            title='自评评分'
            class='my-16'
            style={{
              background: 'linear-gradient(rgb(236, 245, 255) 0%, rgb(255, 255, 255) 10%)'
            }}
          >
            <a-form-item label='总分'>
              <CnBoldSpan>{scoreCount.value}</CnBoldSpan>
            </a-form-item>
            <a-form-item label='评分总结'>
              <a-textarea v-model={[state.summarize, 'value']} row={3}></a-textarea>
            </a-form-item>
            <a-form-item label='附件'>
              <a-upload
                v-model={[state.fileList, 'file-list']}
                // action={baseUrl + '/dd/ddUploadFile'}
                // name='file'
                multiple={true}
                data={(file: File) => file}
                customRequest={async (e: {data: File; file: {uid: string}}) => {
                  console.log(e)
                  // 上传文件前获取授权
                  let res = await ddGetAuth({userDDId: loginUser.value.userId}).catch(err => {})
                  if (!res) return

                  let formData = new FormData()
                  formData.append('file', e.data)
                  formData.append('userDDId', loginUser.value.userId)

                  ddUploadFile(formData)
                    .then(res => {
                      let currentFileIdx = state.fileList.findIndex(item => item.uid === e.file.uid)
                      state.fileList[currentFileIdx].status = 'done'
                      state.annexDataList[currentFileIdx] = {
                        annexFileExtension: res.data.dentry.extension,
                        annexFileId: res.data.dentry.id,
                        annexFileName: res.data.dentry.name,
                        annexFileSize: res.data.dentry.size,
                        annexFileSpaceId: res.data.dentry.spaceId
                      }
                    })
                    .catch(err => {
                      let currentFileIdx = state.fileList.findIndex(item => item.uid === e.file.uid)
                      state.fileList[currentFileIdx].status = 'error'
                      let fileName = state.fileList[currentFileIdx].name
                      message.error(`文件(${fileName})上传失败,请删除后重新上传！`)
                    })
                }}
                onRemove={(file: {uid: string}) => {
                  let currentFileIdx = state.fileList.findIndex(item => item.uid === file.uid)
                  state.annexDataList.splice(currentFileIdx, 1)
                }}
              >
                <a-button>
                  <i class='iconfont icon-ziliaoshangchuan'></i>
                  上传附件
                </a-button>
              </a-upload>
            </a-form-item>
          </CCard>
        </PMContent>
        {/* 
        <ScoreSummarizeModal
          v-models={[[scoreSummarizeVisible.value, 'visible']]}
          onConfirm={handleScoreSummarizeConfirm}
        ></ScoreSummarizeModal> */}
      </PMLayout>
    )
  }
})
